﻿using Susha.Models;
using Susha.Models.Helpers;
using Susha.Models.Pages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Susha.Areas.Default.Controllers
{
    public class GuestController : Controller
    {
        //
        // GET: /Default/Guest/

        public ActionResult Index(Int32? id)
        {
            Int32 pageNo;
            Int32.TryParse(id.ToString(), out pageNo);
            GuestPage guestPage = new GuestPage(pageNo);

            Tuple<String, String> captcha = CommonTools.GetCaptcha();
            Session["Captcha"] = captcha.Item2;
            guestPage.FalseCaptcha = captcha.Item1;

            return View(guestPage);
        }

        [HttpPost]
        public ActionResult Index(GuestComment comment)
        {
            Boolean IsUserCommentHasValue = false;
            Boolean IsCaptchaCorrect = false;

            if (String.IsNullOrWhiteSpace(comment.UserName))
            {
                comment.UserName = "Anonim";
            }
            if (!String.IsNullOrWhiteSpace(comment.UserComment))
            {
                IsUserCommentHasValue = true;
            }
            else
            {
                ModelState.AddModelError("UserComment", "Field cannot be empty");
            }
            if (Session["Captcha"] != null 
                && comment.Captcha != null
                && String.Compare(comment.Captcha, Session["Captcha"].ToString(), true) == 0)
            {
                IsCaptchaCorrect = true;
            }
            else
            {
                ModelState.AddModelError("Captcha", "Captcha is not correct");
            }
            if (IsUserCommentHasValue && IsCaptchaCorrect)
            {
                GuestRepository.Save(comment);
            }
            
            GuestPage guestPage = new GuestPage();
            return View(guestPage);
        }
    }
}
